<template>
  <a-row :gutter="20" class="container">
    <a-col :span="14">
      <a-card class="chart-section">
        <div class="chart-container">
          <div class="bar-item">
            <div class="chart-header">
              <h3 class="analysis-title">题目难度排名</h3>
              <a-radio-group
                v-model="showMode"
                type="button"
                size="small"
                @change="handleModeChange"
                class="mode-switch"
              >
                <a-radio value="hardest">
                  <icon-face-frown-fill />
                  最难TOP3
                </a-radio>
                <a-radio value="easiest">
                  <icon-face-smile-fill />
                  最易TOP3
                </a-radio>
              </a-radio-group>
            </div>
            <!-- 柱状图 -->
            <v-chart
              :option="barChartOption"
              class="bar-chart"
              style="width: 375px; height: 200px"
              @click="handleChartClick"
            />
          </div>
          <div class="user-info-glass">
            <div class="header">
              <icon-user style="color: #4dabf7; font-size: 24px" />
              <div class="user-title">总体情况</div>
            </div>
            <div class="content">
              <div class="score">
                <icon-pen-fill style="margin-right: 8px" />
                <span>平均用户分数: {{ totalInfo.averageScore ?? 0 }}</span>
              </div>
              <div class="accepted-num">
                <icon-check-circle-fill style="margin-right: 8px" />
                <span
                  >平均题目通过数:
                  {{ totalInfo.averageAcceptedQuestionNumber ?? 0 }}</span
                >
              </div>
            </div>
          </div>
        </div>
      </a-card>

      <!-- 下半部分 - 提交记录 -->
      <a-card class="submit-list">
        <!-- 新增说明标题 -->
        <div style="font-size: 12px; padding: 4px 16px; line-height: 1">
          {{
            loginUser.userRole === ACCESS_ENUM.NOT_LOGIN
              ? "用户未登录"
              : loginUser.username + "近五次提交记录"
          }}
        </div>
        <a-list :bordered="false" :data="submitRecord">
          <template #item="{ item }">
            <a-list-item>
              <div
                class="submit-item"
                style="
                  display: flex;
                  align-items: center;
                  gap: 12px;
                  width: 100%;
                "
              >
                <!-- 左侧固定宽度区块 -->
                <div style="flex: 1; min-width: 0">
                  <span style="display: block; text-align: left">{{
                    item.questionTitle
                  }}</span>
                  <span
                    style="
                      display: block;
                      color: #888;
                      font-size: 12px;
                      text-align: left;
                    "
                    >{{ item.createTime }}</span
                  >
                </div>
                <a-tag
                  :color="item.judgeResult === 'Accepted' ? 'green' : 'red'"
                  style="flex-shrink: 0"
                >
                  {{ item.judgeResult }}
                </a-tag>
              </div>
            </a-list-item>
          </template>
        </a-list>
      </a-card>
    </a-col>

    <!-- 右边部分 - 排行榜 -->
    <a-col :span="10">
      <a-card class="ranking">
        <a-list :bordered="false" :data="rankList">
          <template #item="{ item, index }">
            <a-list-item
              :class="{ 'current-user': index === 0 }"
              :style="{
                backgroundColor: index === 0 ? '#f5f5f5' : '',
              }"
            >
              <div class="rank-item">
                <span class="rank-index">{{
                  index === 0 ? "排行榜" : index
                }}</span>
                <span class="rank-name">{{
                  index === 0 ? "学号 : " + item.userId : item.userId
                }}</span>
                <span class="rank-name">{{
                  index === 0 ? "完成题目数" : item.acceptedQuestionNumber
                }}</span>
                <span>
                  {{
                    index === 0
                      ? loginUser.userRole === ACCESS_ENUM.ADMIN
                        ? "管理员不参与排名"
                        : "当前用户排名 :"
                      : "总分 : "
                  }}
                </span>
                <span class="rank-score">
                  {{
                    index === 0
                      ? loginUser.userRole === ACCESS_ENUM.ADMIN
                        ? ""
                        : item.rank
                      : item.score
                  }}</span
                >
              </div>
            </a-list-item>
          </template>
        </a-list>
      </a-card>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { BarChart, PieChart } from "echarts/charts";
import {
  GridComponent,
  LegendComponent,
  TitleComponent,
  TooltipComponent,
} from "echarts/components";
import VChart from "vue-echarts";
import store from "@/store";
import { onMounted, ref } from "vue";
import {
  QuestionControllerService,
  QuestionSubmitControllerService,
  QuestionVO,
  Top10VO,
  UserControllerService,
} from "../../api";
import message from "@arco-design/web-vue/es/message";
import { ACCESS_ENUM } from "@/access/accessEnum";
import { Least5TimeSubmitVO } from "../../api/models/Least5TimeSubmitVO";
import { TotalInfo } from "../../api/models/TotalInfo";
import { useRouter } from "vue-router";

use([
  CanvasRenderer,
  BarChart,
  GridComponent,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
]);
const loginUser = store.state.user.loginUser;
// 横向柱状图配置
const showMode = ref<"hardest" | "easiest">("hardest");
const barChartOption = ref({
  title: {
    left: "center",
    textStyle: {
      color: "#2d3436",
      fontSize: 16,
      fontWeight: "bold",
    },
  },
  tooltip: {
    trigger: "axis",
    formatter: "{b}: {c}%",
  },
  xAxis: {
    type: "value",
    max: 100,
    min: 0,
    axisLabel: {
      width: 300,
      formatter: "{value}%",
    },
  },
  yAxis: {
    type: "category",
    inverse: true,
    data: [] as string[],
    axisLabel: {
      width: 150,
      overflow: "truncate",
    },
  },
  series: [
    {
      type: "bar",
      animationDuration: 1000, // 动画时长
      animationEasing: "cubicOut",
      realtimeSort: true, // 启用实时排序
      data: [] as number[],
      itemStyle: {
        color: "#5470c6",
      },
      label: {
        show: true,
        position: "right",
        formatter: "{c}%",
      },
    },
  ],
  grid: {
    left: "0%", // 减少左边距
    right: "10%", // 减少右边距
    top: "10%", // 调整顶部空间
    bottom: "15%", // 调整底部空间
    containLabel: true,
  },
});
// 柱形图数据
const currentMateData = ref<Array<QuestionVO>>([]);
// 处理切换
const handleModeChange = () => {
  updateChartData(showMode.value);
};
// 点击事件处理
const router = useRouter();
const handleChartClick = (params: any) => {
  if (params.componentType === "series") {
    const dataIndex = params.dataIndex;
    const questionId = currentMateData.value[dataIndex]?.id;

    if (questionId) {
      router.push(`/view/question/${questionId}`);
    } else {
      message.error("无法获取题目ID");
    }
  }
};
// 更新图表数据的方法
const updateChartData = async (mode: "hardest" | "easiest") => {
  const res = await QuestionControllerService.getTop3RatioQuestionVO(
    mode === "hardest"
  );
  if (res.code !== 0) {
    message.error("获取题目数据失败");
    return;
  }
  currentMateData.value = res.data ?? [];
  // 修复1：添加强制类型转换确保数值比较
  const rawData = (res.data ?? []).map((item) => ({
    ...item,
    ratio: Number(item.ratio) || 0, // 确保ratio是数字类型
  }));

  // 修复2：修正排序逻辑
  const sortedData = [...rawData].sort((a, b) => {
    return mode === "hardest"
      ? a.ratio - b.ratio // 最难题目：10% → 30%（升序）
      : b.ratio - a.ratio; // 最简单题目：90% → 70%（降序）
  });

  // 修复3：动态控制坐标轴方向
  const inverse = mode !== "hardest";

  const currentData = sortedData.map((item) => ({
    ...item,
    displayLabel: `Q${item.id ?? 0}`,
    id: item.id,
  }));

  barChartOption.value = {
    ...barChartOption.value,
    tooltip: {
      trigger: "axis",
      // 使用类型断言强制指定为函数类型
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      formatter: (params: any) => {
        const dataIndex = params[0].dataIndex; // 注意这里取数组第一个元素
        const realTitle = currentData[dataIndex].title;
        return `${realTitle}`;
      }, // 关键类型断言
    },
    title: {
      ...barChartOption.value.title,
    },
    yAxis: {
      ...barChartOption.value.yAxis,
      inverse: inverse,
      data: currentData.map((d) => d.displayLabel),
    },
    series: [
      {
        ...barChartOption.value.series[0],
        data: currentData.map((d) => d.ratio ?? 0),
      },
    ],
  };
};

// 系统总体信息
const totalInfo = ref<TotalInfo>({
  averageAcceptedQuestionNumber: 0,
  averageScore: 0,
});

// 近五次提交记录
const submitRecord = ref<Least5TimeSubmitVO[]>([]);

// 排行榜
const rankList = ref<Top10VO[]>([]);

const loadData = async () => {
  try {
    // 并行发起所有请求
    const [, totalInfoRes, submitRecordRes, rankingRes] = await Promise.all([
      updateChartData(showMode.value),
      UserControllerService.getTotalInfo(),
      loginUser.userRole !== ACCESS_ENUM.NOT_LOGIN
        ? QuestionSubmitControllerService.getLeast5TimesSubmit(loginUser.id)
        : Promise.resolve({ code: 0, data: [] }),
      UserControllerService.getTop10Ranking(),
    ]);

    // 处理总体信息
    if (totalInfoRes.code === 0) {
      totalInfo.value = {
        averageAcceptedQuestionNumber:
          totalInfoRes.data?.averageAcceptedQuestionNumber ?? 0,
        averageScore: totalInfoRes.data?.averageScore ?? 0,
      };
    } else {
      message.error(totalInfoRes.message ?? "获取总体信息失败");
    }

    // 处理提交记录
    if (submitRecordRes.code === 0) {
      submitRecord.value = submitRecordRes.data ?? [];
    } else if (loginUser.userRole !== ACCESS_ENUM.NOT_LOGIN) {
      message.error("获取提交记录失败");
    }

    // 处理排行榜
    if (rankingRes.code === 0) {
      rankList.value = rankingRes.data ?? [];
    } else {
      message.error(rankingRes.message ?? "获取排行榜失败");
    }

    // 获取个人排名
    const tempRank: Top10VO = {
      userId: 0,
      score: 0,
      rank: 0,
    };
    // 只有普通用户才会参与排名
    if (loginUser.userRole === ACCESS_ENUM.USR) {
      const myRank = await UserControllerService.getMyRank();
      rankList.value.unshift(myRank.data ?? tempRank);
    } else {
      rankList.value.unshift(tempRank);
    }
  } catch (error) {
    message.error("加载数据时发生错误");
    console.error(error);
  }
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.container {
  height: 68vh;
  padding: 20px;
}

.chart-section {
  height: calc(27.6vh);
  margin-bottom: calc(2.3vh);
}

.chart-container {
  display: flex;
  align-items: center;
  position: relative;
}

.bar-item {
  display: flex;
  flex-direction: column; /* 垂直排列 */
  height: 100%;
  position: relative;
}

.chart-header {
  display: flex;
  align-items: center;
}

.analysis-title {
  margin: 0;
  font-size: 16px;
  color: #1f2d3d;
  font-weight: 600;
}

.bar-chart {
  width: 95%;
  height: 200px; /* 留出头部空间 */
}

/*用户信息*/
.user-info-glass {
  position: absolute;
  right: 20px; /* 向右偏移 20px */
  top: 40%; /* 垂直居中 */
  transform: translateY(-50%);
  width: 300px;
  min-height: 140px;
  background: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.1);
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  padding-bottom: 12px;
  margin-bottom: 15px;
}

.content {
  .score {
    font-size: 18px;
    margin-top: 14px;
    color: #52c41a;
    display: flex;
    align-items: center;
  }

  .accepted-num {
    font-size: 18px;
    margin-top: 20px;
    color: #6c5ce7;
    display: flex;
    align-items: center;
  }
}

.user-title {
  font-size: 20px;
  color: #444;
  margin-right: 16px;
}

/*用户信息*/
.submit-list {
  height: calc(40vh);
}

.submit-item {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 16px;
  padding: 8px 0;
}

.ranking {
  height: calc(70vh);
}

.rank-item {
  display: flex;
  align-items: center;
  width: 100%;
}

.rank-index {
  width: 60px;
  color: #666;
}

.rank-name {
  flex: 1;
}

.rank-score {
  width: 80px;
  text-align: right;
}

.current-user {
  font-weight: bold;
}
</style>
